package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.domain.ReAccount;
import com.ruoyi.system.domain.ReBankBonus;
import com.ruoyi.system.domain.ReBonus;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ReInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 预约开户记录Controller
 * 
 * @author ruoyi
 * @date 2023-12-21
 */
@Controller
@RequestMapping("/system/info")
public class ReInfoController extends BaseController
{
    private String prefix = "system/info";

    @Autowired
    private IReInfoService reInfoService;
    @Autowired
    private IReBankBonusService reBankBonusService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private IReAccountService reAccountService;
    @Autowired
    private IReBonusService reBonusService;


    @Autowired
    private ISysDeptService deptService;

    @RequiresPermissions("system:info:view")
    @GetMapping()
    public String info()
    {
        return prefix + "/info";
    }

    @RequiresPermissions("system:info:view")
    @GetMapping("/acceptOk")
    public String acceptOk()
    {
        return prefix + "/acceptok";
    }

    @RequiresPermissions("system:info:view")
    @GetMapping("/acceptFail")
    public String acceptFail()
    {
        return prefix + "/acceptfail";
    }

    @RequiresPermissions("system:info:view")
    @GetMapping("/openSuccess")
    public String openSuccess()
    {
        return prefix + "/opensuccess";
    }

    @RequiresPermissions("system:info:view")
    @GetMapping("/openFail")
    public String openFail()
    {
        return prefix + "/openfail";
    }

    @RequiresPermissions("system:info:view")
    @GetMapping("/checkFail")
    public String checkFail()
    {
        return prefix + "/checkfail";
    }
    @RequiresPermissions("system:info:view")
    @GetMapping("/checkOk")
    public String checkOk()
    {
        return prefix + "/checkok";
    }

    @RequiresPermissions("system:info:view")
    @GetMapping("/openScoring")
    public String openScoring()
    {
        return prefix + "/openscoring";
    }
    /**
     * 待接洽预约开户记录列表
     */
    @RequiresPermissions("system:info:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ReInfo reInfo)
    {
        reInfo.setAccountState("0");
        startPage();
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        return getDataTable(list);
    }

    /**
     * 接洽成功预约开户记录列表
     */
    @RequiresPermissions("system:info:list")
    @PostMapping("/acceptOkList")
    @ResponseBody
    public TableDataInfo acceptOkList(ReInfo reInfo)
    {
        reInfo.setAccountState("1");
        startPage();
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        return getDataTable(list);
    }

    /**
     * 接洽成功预约开户记录列表
     */
    @RequiresPermissions("system:info:list")
    @PostMapping("/acceptFailList")
    @ResponseBody
    public TableDataInfo acceptFailList(ReInfo reInfo)
    {
        reInfo.setAccountState("2");
        startPage();
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        return getDataTable(list);
    }

    /**
     * 开户成功列表
     */
    @RequiresPermissions("system:info:list")
    @PostMapping("/openSuccessList")
    @ResponseBody
    public TableDataInfo openSuccessList(ReInfo reInfo)
    {
        reInfo.setAccountState("3");
        reInfo.setAccountCheck("0");
        startPage();
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        return getDataTable(list);
    }

    /**
     * 开户失败列表
     */
    @RequiresPermissions("system:info:list")
    @PostMapping("/openFailList")
    @ResponseBody
    public TableDataInfo openFailList(ReInfo reInfo)
    {
        reInfo.setAccountState("4");
        startPage();
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        return getDataTable(list);
    }

    /**
     * 审核成功列表
     */
    @RequiresPermissions("system:info:list")
    @PostMapping("/checkFailList")
    @ResponseBody
    public TableDataInfo checkFailList(ReInfo reInfo)
    {
        reInfo.setAccountCheck("2");
        reInfo.setAccountState("3");
        startPage();
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        return getDataTable(list);
    }
    /**
     * 审核成功列表
     */
    @RequiresPermissions("system:info:list")
    @PostMapping("/checkOkList")
    @ResponseBody
    public TableDataInfo checkOkList(ReInfo reInfo)
    {
        reInfo.setAccountCheck("1");
        reInfo.setAccountState("3");
        startPage();
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        return getDataTable(list);
    }

    /**
     * 个人积分信息列表
     */
    @RequiresPermissions("system:info:list")
    @PostMapping("/openScoringList")
    @ResponseBody
    public TableDataInfo openScoringList(ReInfo reInfo)
    {
        reInfo.setAccountCheck("1");
        reInfo.setAccountState("3");
        reInfo.setCreateBy(getLoginName());
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        return getDataTable(list);
    }
    /**
     * 导出预约开户记录列表
     */
    @RequiresPermissions("system:info:export")
    @Log(title = "预约开户记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ReInfo reInfo)
    {
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        ExcelUtil<ReInfo> util = new ExcelUtil<ReInfo>(ReInfo.class);
        return util.exportExcel(list, "预约开户记录数据");
    }

    /**
     * 新增预约开户记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存预约开户记录
     */
    @RequiresPermissions("system:info:add")
    @Log(title = "预约开户记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ReInfo reInfo)
    {
        reInfo.setCreateBy(getLoginName());
        return toAjax(reInfoService.insertReInfo(reInfo));
    }

    /**
     * 修改预约开户记录
     */
    @RequiresPermissions("system:info:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ReInfo reInfo = reInfoService.selectReInfoById(Long.valueOf(id));
        mmap.put("reInfo", reInfo);
        return prefix + "/edit";
    }


    /**
     * 开户成共确认
     */
    @RequiresPermissions("system:info:edit")
    @GetMapping("/acceptOkEdit/{id}")
    public String acceptOkEdit(@PathVariable("id") String id, ModelMap mmap)
    {
        ReInfo reInfo = reInfoService.selectReInfoById(Long.valueOf(id));
        mmap.put("reInfo", reInfo);
        return prefix + "/acceptokedit";
    }

    /**
     * 开户成共确认
     */
    @RequiresPermissions("system:info:edit")
    @GetMapping("/openSuccessEdit/{id}")
    public String openSuccessEdit(@PathVariable("id") String id, ModelMap mmap)
    {
        ReInfo reInfo = reInfoService.selectReInfoById(Long.valueOf(id));
        mmap.put("reInfo", reInfo);
        return prefix + "/opensuccessedit";
    }

    /**
     * 修改保存预约开户记录
     */
    @RequiresPermissions("system:info:edit")
    @Log(title = "预约开户记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ReInfo reInfo)
    {


        if(reInfo!=null){
            if(reInfo.getAccountState()!=null&&!reInfo.getAccountState().isEmpty() && reInfo.getAccountState().equals("0")){

                SysUser user=getSysUser();
                SysDept dept= deptService.selectDeptById(user.getDeptId());
                reInfo.setUserName(user.getUserName());
                reInfo.setUserId(user.getUserId());
                reInfo.setUpdateBy(getLoginName());
                reInfo.setDeptName(dept.getDeptName());
            }
            if(reInfo.getAccountState()!=null&&!reInfo.getAccountState().isEmpty() && reInfo.getAccountState().equals("1")){

                SysUser user=getSysUser();

                reInfo.setReception(user.getUserName());
                reInfo.setReceptionId(user.getUserId());


            }
            if(reInfo.getAccountState()!=null&&!reInfo.getAccountState().isEmpty() && reInfo.getAccountState().equals("2")){

                SysUser user=getSysUser();

                reInfo.setReception(user.getUserName());
                reInfo.setReceptionId(user.getUserId());

            }
            if(reInfo.getAccountState()!=null&&!reInfo.getAccountState().isEmpty() && reInfo.getAccountState().equals("3")){
                if(reInfo.getAccountCheck()==null || reInfo.getAccountCheck().isEmpty() ){
                    //如果开户成功 则审核状态改为待审核
                    reInfo.setAccountCheck("0");
                    reInfo.setSuccessDate(new Date());
                    reInfo.setConfirm(getSysUser().getUserName());
                    reInfo.setConfirmId(getUserId());
                }


            }
            if(reInfo.getAccountState()!=null&&!reInfo.getAccountState().isEmpty() && reInfo.getAccountState().equals("4")){
                if(reInfo.getAccountCheck()==null || reInfo.getAccountCheck().isEmpty() ){
                    //如果开户失败

                    reInfo.setSuccessDate(new Date());
                    reInfo.setConfirm(getSysUser().getUserName());
                    reInfo.setConfirmId(getUserId());
                }


            }
            //审核成功则需要根据开户行的积分设定 来添加积分 并且添加分销积分
            if(reInfo.getAccountCheck()!=null&&!reInfo.getAccountCheck().isEmpty() && reInfo.getAccountCheck().equals("1")){
                ReInfo info=reInfoService.selectReInfoById(reInfo.getId());
                ReBankBonus deptbank=reBankBonusService.selectReBankBonusByOrgIdAndAccountType(info.getOrgId(),info.getAccountType());
                reInfo.setBonus(deptbank.getBonus());
                reInfo.setCheckDate(new Date());
                reInfo.setCheckUser(getSysUser().getUserName());
                reInfo.setCheckUserId(getUserId());
                reInfo.setCashState("0");
                //审核成功后 如果是二三级用户则需要计算上级的分销积分到分销积分榜

                SysUser myuser=userService.selectUserByOpenId(info.getOpenId());

                //二级分销 则需要计算他的一级分销的奖励积分  ；先判断是否有上级分销 如果有这个用户目前就是二级分销 要给他的上级（父级）计算 分销积分
                if(myuser!=null && myuser.getRatingId()!=null){
                    //父级用户
                    SysUser fuser=userService.selectUserById(myuser.getRatingId());
                    if(fuser!=null) {
                        ReAccount reAccount = new ReAccount();
                        //根据账户性质和分销等级查询奖励积分是多少
                        ReBonus reBonus = reBonusService.selectReBonusByAccountTypeAndLevel(info.getAccountType());
                        reAccount.setUserId(fuser.getUserId());
                        reAccount.setUserName(fuser.getUserName());
                        reAccount.setRatingId(myuser.getUserId());
                        reAccount.setRatingName(myuser.getUserName());
                        reAccount.setBonus(reBonus.getFbonus());
                        //reAccount.setRating("1");
                        reAccount.setReNumber(info.getReNumber());
                        reAccount.setReInfiId(Long.valueOf(info.getId()));
                        reAccount.setCompany(info.getCompanyName());
                        reAccount.setAcceptDate(info.getAcceptDate());
                        reAccount.setAccountType(info.getAccountType());
                        reAccount.setOrgName(info.getOrgName());
                        reAccount.setCashState("0");
                        reAccount.setCreateBy(info.getCreateBy());
                        reAccount.setOpenId(myuser.getOpenId());
                        reAccountService.insertReAccount(reAccount);
                    }
                    //三级分销 则需要计算他的一级分销和二级分销的奖励积分
                    if(fuser.getRatingId()!=null){
                        //爷级用户
                        SysUser guser=userService.selectUserById(fuser.getRatingId());
                        ReAccount reAccount1=new ReAccount();

                        ReBonus fBonus=reBonusService.selectReBonusByAccountTypeAndLevel(info.getAccountType());
                        //给父级分销算奖励积分
                        if(guser!=null) {
                            reAccount1.setUserId(guser.getUserId());
                            reAccount1.setUserName(guser.getUserName());
                            reAccount1.setRatingId(fuser.getUserId());
                            reAccount1.setRatingName(fuser.getUserName());
                            reAccount1.setBonus(fBonus.getGbonus());
                            //reAccount1.setRating("1");
                            reAccount1.setReNumber(info.getReNumber());
                            reAccount1.setReInfiId(Long.valueOf(info.getId()));
                            reAccount1.setCompany(info.getCompanyName());
                            reAccount1.setAcceptDate(info.getAcceptDate());
                            reAccount1.setAccountType(info.getAccountType());
                            reAccount1.setOrgName(info.getOrgName());
                            reAccount1.setCashState("0");
                            reAccount1.setCreateBy(info.getCreateBy());
                            reAccount1.setOpenId(guser.getOpenId());
                            reAccountService.insertReAccount(reAccount1);
                        }
                       //给爷爷级分销算奖励积分
//                        if(guser!=null) {
//                            ReAccount reAccount2 = new ReAccount();
//                            reAccount2.setUserId(guser.getUserId());
//                            reAccount2.setUserName(guser.getUserName());
//                            reAccount2.setRatingId(myuser.getUserId());
//                            reAccount2.setRatingName(myuser.getUserName());
//                            reAccount2.setBonus(fBonus.getGbonus());
//                            reAccount2.setRating("2");
//                            reAccount2.setReNumber(info.getReNumber());
//                            reAccount2.setReInfiId(Long.valueOf(info.getId()));
//                            reAccount2.setCompany(info.getName());
//                            reAccount2.setAcceptDate(info.getAcceptDate());
//                            reAccount2.setAccountType(info.getAccountType());
//                            reAccount2.setOrgName(info.getOrgName());
//                            reAccount2.setCashState("0");
//                            reAccount1.setCreateBy(info.getCreateBy());
//                            reAccountService.insertReAccount(reAccount2);
//                        }

                    }
                }

            }

        }
        return toAjax(

                reInfoService.updateReInfo(reInfo));
    }

    /**
     * 删除预约开户记录
     */
    @RequiresPermissions("system:info:remove")
    @Log(title = "预约开户记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(reInfoService.deleteReInfoByIds(ids));
    }

    /**
     * 开户积分提现
     */
    @RequiresPermissions("system:info:cash")
    @Log(title = "开户积分提现", businessType = BusinessType.UPDATE)
    @PostMapping( "/cash")
    @ResponseBody
    public AjaxResult cash(String ids)
    {
        String[] accountIds = Convert.toStrArray(ids);
        for (String id : accountIds)
        {
            ReInfo reInfo=reInfoService.selectReInfoById(Long.valueOf(id));
            reInfo.setCashState("1");
            reInfoService.updateReInfo(reInfo);

        }

        return toAjax(accountIds.length);
    }
}
